package com.simple.dsrouter.factory;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.core.io.Resource;

import com.simple.dsrouter.config.DataSourceConfig;
import com.simple.dsrouter.config.DataSourcesConfig;
import com.simple.dsrouter.config.TableConfig;
import com.thoughtworks.xstream.XStream;

public class SimpleDataSourceFactory {

	private Resource configLocation;

	private static final String DEFAULT_DATASOURCE_XML = "/datasource-config.xml";

	public Map<Integer, List<DataSourceConfig>> buildDataSourceKeyMap() throws IOException {
		InputStream input = null;
		if (configLocation != null) {
			input = this.configLocation.getInputStream();
		} else {
			input = this.getClass().getResourceAsStream(DEFAULT_DATASOURCE_XML);
		}
		XStream xs = new XStream();
		xs.processAnnotations(new Class[] { DataSourcesConfig.class, DataSourceConfig.class, TableConfig.class });
		DataSourcesConfig datasourcesConfig = (DataSourcesConfig) xs.fromXML(input);

		Map<Integer, List<DataSourceConfig>> dataSourceKeyMap = null;
		if (datasourcesConfig != null) {
			List<DataSourceConfig> datasources = datasourcesConfig.getDatasources();
			if (datasources != null && datasources.size() > 0) {
				dataSourceKeyMap = new HashMap<Integer, List<DataSourceConfig>>();
				for (DataSourceConfig dataSource : datasources) {
					List<DataSourceConfig> list = dataSourceKeyMap.get(dataSource.getGroupId());
					if (list == null) {
						list = new ArrayList<DataSourceConfig>(datasources.size());
						dataSourceKeyMap.put(Integer.valueOf(dataSource.getGroupId()), list);
					}
					list.add(dataSource);
				}
			}
		}
		return dataSourceKeyMap;
	}

	public void setConfigLocation(Resource configLocation) {
		this.configLocation = configLocation;
	}

}
